Building a Python Flask Website a Beginner-Friendly Guide
Total Page:16
File Type:pdf, Size:1020Kb
Building a Python Flask Website A beginner-friendly guide PythonHow.com Copyright © 2016 PythonHow.com. All rights reserved. 1 Preface This book contains a quick guide on understanding and using the Python flask framework for building a simple website. This tutorial does not intend to be a complete guide on the flask framework, but a complete guide on creating a static website with Python from scratch to deployment on a production server. The book is great for people who have never programmed before and who want to get started with Python for building web applications. 2 Building a Python Flask Website Table of contents Your first Flask website ...................................................................................... 4 How building a website with Python work ......................................................... 5 How a Flask app works ....................................................................................... 6 HTML templates in flask ..................................................................................... 8 Adding more pages to the website ................................................................... 10 Adding a navigation menu to the website ........................................................ 12 Adding CSS styling to your website .................................................................. 16 Using virtualenv with your flask app ................................................................ 21 Deploying your Python web application to the Heroku cloud .......................... 24 Maintaining your Python web app .................................................................... 27 3 Your first Flask website Why not making a website before you even learn how to make a website? Just something as simple as this: Yes, it’s just a page with some plain text, but it is still called a website and that’s how it starts. Python is concise so it takes only seven lines of code to build what you see in the screenshot. Let’s do it. Insert the following lines of Python code inside an empty text file, and name the file something like hello.py. from flask import Flask app = Flask(__name__) @app.route('/') def home(): return "Hey there!" if __name__ == '__main__': app.run(debug=True) As you can see we are importing the flask library in the first line. If you don’t have that library installed, you will get an error. To install flask, simply type in pip install flask your computer terminal/command line. Once you have made sure flask is installed, simply run the hello.py script. Once you run the script, your website should be now live on your local machine and it can be viewed by visiting localhost:5000 in your browser. Let’s move on! 4 How building a website with Python works Before building something more attractive instead of just a webpage with plain text, let’s first make sure you understand how generating websites with Python works. Think about the user typing in your website URL in their browser. When the user enters the URL in the browser, they are making a request to the web server. As a developer, you would have to write some Python code to handle requests and deal with CGI which is a standard environment that Python and other web development programming languages use to create web pages dynamically. And you would have to write the same code over and over again for every web app that you built. Now, because that is a repetitive task, someone put all that code together and created a bunch of Python files. These bunch of files were called flask. So, flask is a framework which when loaded in Python automatically executes the routine code and let’s you focus on the specific parts of your website. When we type in pip install flask in the command line, we are downloading the flask framework from its online repositories and when we import flask we are making the framework available in our current script and we can use its features easily there. Now, before making a more advanced website, let’s go and explain all the lines of the code we have so far in the next lesson of the tutorial. 5 How a Flask app works In this lesson you will learn how a flask web app works. The code we have so far is a typical flask script that builds a simple website. So, we’re going to explain what that code does line by line. This is what we have so far: from flask import Flask app = Flask(__name__) @app.route('/') def home(): return "Hey there!" if __name__ == '__main__': app.run(debug=True) In line 1 you are making available the code you need to build web apps with flask. flask is the framework here, while Flask is a Python class datatype. In other words, Flask is the prototype used to create instances of web application or web applications if you want to put it simple. So, once we import Flask, we need to create an instance of the Flask class for our web app. That’s what line 3 does. __name__ is a special variable that gets as value the string "__main__" when you’re executing the script. We’ll go back to that in a moment. In lines 5-7 we are defining a function that returns the string “Hey there!”. That function is mapped to the home ‘/’ URL. That means when the user navigates to localhost:5000 , the home function will run and it will return its output on the webpage. If the input to the route method was something else, let’s say ‘/about/’ , the function output would be shown when the user visited localhost:5000/about/ . How practical is that? Then we have the mysterious lines 9 and 10. Something you should know is that Python assigns the name "__main__" to the script when the script is executed. If the script is imported from another script, the script keeps it given name (e.g. hello.py). In our case we are executing the script. Therefore, __name__ will be equal to "__main__" . That means the if conditional statement is satisfied and the app.run() method will be executed. This technique allows the programmer to have control over script’s behavior. 6 Notice also that we are setting the debug parameter to true . That will print out possible Python errors on the web page helping us trace the errors. However, in a production environment, you would want to set it to False as to avoid any security issues. So far, so good! We have a running website with some content returned by the Python function. As you can imagine, returning plain strings from a function doesn’t take us anywhere far. If you want to make something more serious and more visually appealing, you would want to incorporate HTML files along your Python file and have your Python code return HTML pages instead of plain strings. You will do just that in the next lesson. 7 HTML templates in flask In this part of the tutorial, you will learn to return HTML pages through your Python script using the flask render_template method. At the end of this lesson, your website will look like this: As you see, we don’t have plain text anymore, but text with various formats. That is made possible by returning an HTML template instead of a plain Python string. Let’s see how I did that. Create an empty file, name it something like home.html and put the following HTML code inside it: <!DOCTYPE html> <html> <body> <h1>My Personal Website</h1> <p>Hi, this is my personal website.</p> </body> </html> As you already know HTML is a markup language used to render webpages. Try to remember these three things about creating HTML pages: An HTML document must start with a declaration that specifies the document type: <!DOCTYPE html>. The HTML document itself always begins with <html> and ends with </html>. The visible part of the HTML document is between <body> and </body>. The area outside of that is used to reference Javascript files, CSS, or other features. 8 The flask framework has been written in a way so that it looks for HTML template files in a folder that should be named templates . So, you should create such an empty folder and then put all the HTML templates in there. Here is how the web app directory tree should like at this point: So, the Python script stays outside of the templates folder. Let’s now edit the Python code so that it reads the HTML template and returns it to the webpage. Here is the updated version: from flask import Flask, render_template app = Flask(__name__) @app.route('/') def home(): return render_template('home.html') if __name__ == '__main__': app.run(debug=True) The highlighted lines are the ones to have been updated. And what we did is we imported the render_template method from the flask framework and then we passed an HTML file to that method. The method will generate a jinja2 template object out of that HTML and return it to the browser when the user visits associated URL. So, going to localhost:5000 now should display the webpage shown in screenshot at the beginning of this lesson. Great! Let’s expand our website even more. 9 Adding more pages to the website In this lesson you will learn how to add more pages to your flask website. We will quickly add an About page. For that, you need to create an about.html file inside the templates folder. The HTML code would be as follows: <!DOCTYPE html> <html> <body> <h1>About me</h1> <p>This is a portfolio site about anything that can be put in a portfolio.</p> </body> </html> Second, you need to render the HTML with Python by adding a second function to the hello.py Python script. from flask import Flask, render_template app = Flask(__name__) @app.route('/') def home(): return render_template('home.html') @app.route('/about/') def about(): return render_template('about.html') if __name__ == '__main__': app.run(debug=True) Run the Python script and go to localhost:5000/about and you will see the new page.